<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图 -->
    <el-card>
      <!-- 头部警告 -->
      <el-alert title="注意：只允许为第三级设置相关参数！" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选中商品分类 -->
      <el-row class="cat_opt" type="flex" align="middle">
        <el-col :span="4"><span>选择商品分类</span></el-col>
        <el-col :span="8">
          <el-cascader v-model="selectedCateId" :options="cateList" :props="cascaderProp" clearable @change="handleChange"></el-cascader>
        </el-col>
      </el-row>

      <!-- 选择参数种类 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addOne()">添加参数</el-button>
          <!-- 列表 -->
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(scope.row, index)">
                  {{ item }}
                </el-tag>
                <!-- 动态添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="editOne(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="removeOne(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addOne()">添加属性</el-button>
          <!-- 列表 -->
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleClose(scope.row, index)">
                  {{ item }}
                </el-tag>
                <!-- 动态添加tag -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
            <!-- 操作 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="editOne(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="removeOne(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数 -->
    <el-dialog
      :title="type == 'add' ? (activeName == 'many' ? '添加参数' : '添加属性') : activeName == 'many' ? '修改参数' : '修改属性'"
      :visible.sync="dialogAddParamVisible"
      @close="addParamDialog()"
    >
      <el-form :model="addForm" ref="addForm" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-form-item :label="activeName == 'many' ? '参数名称' : '属性名称'" prop="attr_name" placeholder="请输入参数名称">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('addForm')">确定</el-button>
          <el-button @click="dialogAddParamVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      type: '',
      // 级联选择框
      cascaderProp: {
        //指定级联对象配置选项
        // expandTrigger: 'hover' ,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedCateId: [], //选择分类id
      cateList: [], //所有分类列表
      //Tabs
      activeName: 'many',
      manyTableData: [], //动态参数数据
      onlyTableData: [], //静态属性数据
      //动态添加tag
      inputVisible: false, //控制input框输入
      inputValue: '', //绑定input的值
      //添加参数
      dialogAddParamVisible: false,
      addForm: {
        attr_name: ''
      },
      rules: {
        cat_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  computed: {
    isBtnDisabled() {
      console.log('selectedCateId', this.selectedCateId.length)
      if (this.selectedCateId.length == 0) {
        //没有选择分类
        return true
      }
      return false
    },
    cateId() {
      if (this.selectedCateId.length > 0) {
        //选择分类
        return this.selectedCateId[this.selectedCateId.length - 1]
      }
      return null
    }
  },
  mounted() {
    // this.getList();
    this.getCateList()
  },
  methods: {
    getList() {
      //获取所有分类列表
      if (this.selectedCateId.length != 3) {
        //选的不是第三级分类
        this.selectedCateId = []
        this.manyTableData = []
        return
      }
      const data = {
        sel: this.activeName
      }
      this.$http
        .get(`/categories/${this.cateId}/attributes`, { params: data })
        .then(res => {
          res = res.data
          if (res.meta.status != 200) {
            //报错就直接返回
            this.$message({ type: 'error', message: res.meta.msg })
            return
          }
          //处理attr_vals
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
            //给动态tag赋值
            item.inputVisible = false
            item.inputValue = ''
          })

          console.log('data', res.data)
          if (this.activeName == 'many') {
            this.manyTableData = res.data
          } else {
            this.onlyTableData = res.data
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    getCateList() {
      //获取所有分类列表
      this.$http
        .get('/categories')
        .then(res => {
          res = res.data
          if (res.meta.status != 200) {
            //报错就直接返回
            this.$message({ type: 'error', message: res.meta.msg })
            return
          }
          this.cateList = res.data
          console.log('cateList', this.cateList)
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleChange() {
      //级联点击事件
      console.log('selectedCateId', this.selectedCateId)
      this.getList() //获取所有分类列表
    },
    handleTabsClick() {
      //tabs点击事件
      console.log('activeName', this.activeName)
      this.getList() //获取所有分类列表
    },
    addParamDialog() {
      //关闭弹窗时,重置表单
      this.$refs.addForm.resetFields()
    },
    addOne() {
      //添加参数显示
      this.type = 'add'
      this.dialogAddParamVisible = true
    },
    editOne(row) {
      this.type = 'edit'
      this.addForm = JSON.parse(JSON.stringify(row))
      this.dialogAddParamVisible = true
    },
    onSubmit(formName) {
      console.log('addForm', this.addForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.type == 'add') {
            this.addSubmit()
          } else {
            this.editSubmit()
          }
        }
      })
    },
    addSubmit() {
      //新增提交数据
      const data = {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/categories/${this.cateId}/attributes`, data)
          .then(res => {
            res = res.data
            if (res.meta.status != 201) {
              //报错就直接返回
              this.$message({ type: 'error', message: res.meta.msg })
              return
            }
            this.dialogAddParamVisible = false
            this.getList()
            this.$message({ type: 'success', message: res.meta.msg })
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    editSubmit() {
      //修改提交数据
      const data = {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .put(`/categories/${this.cateId}/attributes/${this.addForm.attr_id}`, data)
          .then(res => {
            res = res.data
            if (res.meta.status != 200) {
              //报错就直接返回
              this.$message({ type: 'error', message: res.meta.msg })
              return
            }
            this.dialogAddParamVisible = false
            this.getList()
            this.$message({ type: 'success', message: res.meta.msg })
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    removeOne(row) {
      //删除
      this.$confirm(`确定删除${row.attr_name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete(`/categories/${this.cateId}/attributes/${row.attr_id}`)
          .then(res => {
            res = res.data
            if (res.meta.status != 200) {
              //报错就直接返回
              this.$message({ type: 'error', message: res.meta.msg })
              return
            }
            this.getList()
            this.$message({ type: 'success', message: res.meta.msg })
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    handleInputConfirm(row) {
      //动态添加tag文本框失去焦点或按下enter事件
      if (row.inputValue.trim().length == 0) {
        //不合法,空格
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    showInput(row) {
      //动态添加tag文本框失去焦点或按下enter事件
      row.inputVisible = true
      // 页面渲染完之后
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus() //让文本框自动获取焦点
      })
    },
    saveAttrVals(row) {
      //将attr_vals保存操作
      const data = {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      }
      console.log('data', data)
      this.$http
        .put(`/categories/${this.cateId}/attributes/${row.attr_id}`, data)
        .then(res => {
          res = res.data
          if (res.meta.status != 200) {
            //报错就直接返回
            this.$message({ type: 'error', message: res.meta.msg })
            return
          }
          this.$message({ type: 'success', message: res.meta.msg })
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleClose(row, index) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px;
}
.el-tag {
  margin: 5px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
